import React, {Component} from "react";
import PubSub from 'pubsub-js'
import axios from "axios";


export default class Search extends Component {

    // search = () => {
    //     // 获取用户输入（连续解构赋值+重命名）
    //     const {keyWordElement: {value: keyWord}} = this
    //     // 发送请求前通知List更新状态
    //     PubSub.publish('zhouxiaoge', {isFirst: false, isLoading: true});
    //     // 发送网络请求
    //     axios.get(`https://api.github.com/search/users?q=${keyWord}`).then(
    //         response => {
    //             // 请求成功后通知Listp更新状态
    //             PubSub.publish('zhouxiaoge', {isLoading: false, users: response.data.items});
    //         },
    //         error => {
    //             // 请求失败后通知List更新状态
    //             PubSub.publish('zhouxiaoge', {isLoading: false, err: error.message});
    //         }
    //     )
    // }

    // search = () => {
    //     // 未优化版本
    //     fetch(`https://api.github.com/search/users?q=${keyWord}`).then(
    //         response => {
    //             console.log('联系服务器成功了');
    //             return response.json();
    //         },
    //         reason => {
    //             console.log('联系服务器失败了', reason);
    //             return new Promise(()=>{});
    //         }
    //     ).then(
    //         response => {
    //             console.log('获取数据成功了', response);
    //         },
    //         reason => {
    //             console.log('获取数据失败了',reason)
    //         }
    //     );
    // }

    // search = () => {
    //     // 优化后的
    //     fetch(`https://api.github.com/search/users?q=${keyWord}`).then(
    //         response => {
    //             console.log('联系服务器成功了');
    //             return response.json();
    //         }
    //     ).then(
    //         response => {
    //             console.log('获取数据成功了', response);
    //         }
    //     ).catch(
    //         reason => {
    //             console.log('请求出错', reason);
    //         }
    //     );
    // }

    search = async () => {
        const {keyWordElement: {value: keyWord}} = this
        try {
            PubSub.publish('zhouxiaoge', {isFirst: false, isLoading: true});
            const response = await fetch(`https://api.github.com/search/users?q=${keyWord}`)
            const data = await response.json();
            console.log(data)
            PubSub.publish('zhouxiaoge', {isLoading: false, users: data.items});
        } catch (error) {
            PubSub.publish('zhouxiaoge', {isLoading: false, err: error.message});
        }
    }

    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">搜索github用户</h3>
                <div>
                    <input ref={c => this.keyWordElement = c} type="text" placeholder="输入关键字点击进行搜索"/>&nbsp;
                    <button onClick={this.search}>Search</button>
                </div>
            </section>
        )
    }
};